/*
 * @(#)MPQueryConfigProducer.java
 * Date 2013-08-13
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.mpq.inject;

import java.io.InputStream;

import javax.enterprise.inject.Produces;

import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.InjectionPoint;

import org.yaml.snakeyaml.Yaml;

import us.hornerscorners.lamppost.exception.ValidationException;

import us.hornerscorners.lamppost.registry.config.AdhocQueryConfig;


/**
 *
 * @author jim
 */
public class MPQueryConfigProducer {

    /**
     * Method description
     *
     *
     * @param is
     *
     * @return
     */
    public static AdhocQueryConfig readConfig(InputStream is) throws ValidationException {

        Yaml yaml = new Yaml(new MPQueryConfigConstructor());
        AdhocQueryConfig result = yaml.loadAs(is, AdhocQueryConfig.class);

        result.validate();

        return result;
    }

    /**
     * Method description
     *
     *
     *
     * @return
     */
    @MPQTarget
    @Produces
    public AdhocQueryConfig produce(InjectionPoint injectionPoint)
            throws ValidationException {

        Annotated ann = injectionPoint.getAnnotated();
        MPQTarget target = ann.getAnnotation(MPQTarget.class);

        String filename = target.value();

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream is = cl.getResourceAsStream(filename);

        return readConfig(is);
    }
}
